package SGUI

import (
	. "SGEngine2"
	"dom4g"
	"strconv"
)

var DefaultFont *FTFont

func init() {
	DefaultFont = nil
}

type Text struct {
	WidgetInfo
	Font  *FTFont
	Text  string
	Color Color4
}

func (t *Text) OnUpdate() {

}
func (t *Text) GetWidgetInfo() *WidgetInfo {

	return &t.WidgetInfo
}

func (t *Text) OnAttach(node *Node) {

}

func (this *Text) OnEnable(node *Node) {
	this.Component2D.OnAttach(node)
	node.GetRender().RenderMesh, this.Node.Bounds = this.Font.GenFTLabelMesh(this.Text, this.GetPivotOffset(), this.Color)
	node.GetRender().Mat = this.Font.FontMat
}

func (this *Text) OnDisable(node *Node) {
	node.GetRender().RenderMesh.Destory()
	node.SetRender(nil)
}

func (this *Text) GetSize() (float32, float32) {
	b := this.Node.Bounds
	return float32(b.Max.X - b.Min.X), float32(b.Max.Y - b.Min.Y)
}

func (this *Text) GetLayoutSize() (float32, float32) {
	Width, Height := this.GetSize()
	return Width + this.Margin.Left + this.Margin.Right, Height + this.Margin.Top + this.Margin.Bottom
}

func (t *Text) SetText(text string) {

	t.Node.GetRender().RenderMesh, t.Node.Bounds = t.Font.GenFTLabelMesh(text, t.GetPivotOffset(), t.Color)
}

func (f *Text) SetColor(c4 Color4) {
	f.Color = c4
	f.Node.GetRender().RenderMesh, f.Node.Bounds = f.Font.GenFTLabelMesh(f.Text, f.GetPivotOffset(), c4)
}

func (this *Text) OnDetach(node *Node) {
	this.OnDisable(node)
}

func (t *Text) SetColorRGBA(r, g, b, a float32) {
	t.Color.R = r
	t.Color.G = g
	t.Color.B = b
	t.Color.A = a
	t.Node.GetRender().RenderMesh, t.Node.Bounds = t.Font.GenFTLabelMesh(t.Text, t.GetPivotOffset(), t.Color)
}

func GenTextByXML(elem *dom4g.Element, node *Node, tw *TopWidget, p IWidget) IWidget {
	newWidget := &Text{}
	newWidget.Node = node
	newWidget.Top = tw

	if DefaultFont == nil {
		DefaultFont = NewFTFont("C:\\Windows\\Fonts\\msyhbd.ttf", 14)
	}
	newWidget.Font = DefaultFont

	parseNodeAttrs(elem, newWidget, p)
	if v, ok := elem.AttrValue("Text"); ok {
		newWidget.Text = v
	}
	if v, ok := elem.AttrValue("Color"); ok {
		if v[0] == '#' {
			r, _ := strconv.ParseInt(v[1:3], 16, 32)
			g, _ := strconv.ParseInt(v[3:5], 16, 32)
			b, _ := strconv.ParseInt(v[5:7], 16, 32)
			newWidget.Color = NewColor4Byte(float32(r), float32(g), float32(b), 255)
		}
	}
	return newWidget
}
